import wave
import matplotlib.pyplot as plt
import numpy as np
import os

import keras

def get_wav_mfcc(wav_path):
    import scipy.io.wavfile as wf

    # f = wave.open(wav_path, 'rb')
    l = []  # 在函数内部定义空列表
    import scipy.io.wavfile as wf
    import librosa
    # y, sr = librosa.load(wav_path, sr=16000)


    # f = wave.open("D:/work/bagpipe/trainvoice5/train/abnormal_treble.wav", 'rb')
    # params = f.getparams()
    # # print("params:",params)
    # nchannels, sampwidth, framerate, nframes = params[:4]
    # strData = f.readframes(nframes)#读取音频，字符串格式
    # waveData = np.frombuffer(strData,dtype=np.int16)#将字符串转化为int
    #
    # waveData = waveData*1.0/(max(abs(waveData)))#wave幅值归一化
    #
    #
    #
    # waveData = np.reshape(waveData,[nframes,nchannels]).T
    # f.close()
    # print(waveData[0])
    # print(len(waveData[0]))

    wav, sr = librosa.load(wav_path, sr=16000)

    normalized_waveform  = wav/np.max(np.abs(wav))

    # intervals = librosa.effects.split(wav, top_db=20)
    # wav_output = []
    # for sliced in intervals:
    #     wav_output.extend(wav[sliced[0]:sliced[1]])
    # assert len(wav_output) >= 8000, "有效音频小于0.5s"
    # wav_output = np.array(wav_output)
    # ps = librosa.feature.melspectrogram(y=wav_output, sr=sr, hop_length=256).astype(np.float32)
    # ps = ps[np.newaxis, ..., np.newaxis]



    # print(waveData)

    # plt.rcParams['savefig.dpi'] = 300 #图片像素
    # plt.rcParams['figure.dpi'] = 300 #分辨率
    # plt.specgram(waveData[0],Fs = framerate, scale_by_freq = True, sides = 'default')
    # plt.ylabel('Frequency(Hz)')
    # plt.xlabel('Time(s)')
    # plt.title('wa')
    # plt.show()

    ### 对音频数据进行长度大小的切割，保证每一个的长度都是一样的【因为训练文件全部是1秒钟长度，16000帧的，所以这里需要把每个语音文件的长度处理成一样的】
    # data = list(np.array(waveData[0]))
    # data = list(np.array(waveData[0]))

    data = list(normalized_waveform)

    print(len(data))
    l.append(len(data))
    while len(data)>300000:
        del data[len(data)-1]  #删除最后一个
        del data[0]    #删除第一个
    # print(len(data))
    while len(data)<300000:
        data.append(0)
    print(len(data))

    data=np.array(data)

    # 平方之后，开平方，取正数，值的范围在  0-1  之间
    data = data ** 2
    data = data ** 0.5




        # 其他代码...


    return data


model = keras.models.load_model("D:/graduation design/DNN/model.h5")  # 加载训练模型
wavs = []
wavs.append(get_wav_mfcc("D:/Pycharm/trainvoice5/test/abnormal_treble/abnormal_treble+++.wav") )# 使用某一个文件
X = np.array(wavs)
#print(X.shape)
result = model.predict(X)  # 识别出第一张图的结果，多张图的时候，把后面的[0] 去掉，返回的就是多张图结果
print("识别结果", result)
